package com.soujiayi.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.soujiayi.adapter.SkimHistoryListAdapter;
import com.soujiayi.model.Mall;
import com.soujiayi.model.Product;
import com.soujiayi.model.SkimHistory;
import com.soujiayi.net.HttpRequester;
import com.soujiayi.net.NetworkUtils;
import com.soujiayi.store.DatabaseManager;
import com.soujiayi.util.Constants;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;


public class SkimHistoryActivity extends Activity {
	
	private ListView skimHistoryListView;
	private SkimHistoryListAdapter skimHistoryListAdapter;
	private List<SkimHistory> skimHistoryList = new ArrayList<SkimHistory>();
	private TextView tv_no_record;
	
	private DatabaseManager databaseManager = new DatabaseManager(SkimHistoryActivity.this);
	
	private Handler goodsDetailHandler;
	private HttpRequester httpRequester;
	private String sid = "";
	
	ProgressDialog progressDialog;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		((MyApplication) this.getApplication()).addActivity(this);
		setContentView(R.layout.skim_history);
		
		initSkimHistory();
	}
	
	public void initSkimHistory(){
		skimHistoryListView = (ListView) findViewById(R.id.lv_skim_history);
        
		skimHistoryListAdapter = new SkimHistoryListAdapter(this, skimHistoryList);
		skimHistoryListView.setAdapter(skimHistoryListAdapter);
		
		tv_no_record = (TextView) findViewById(R.id.tv_skim_history_no_record);
        
		progressDialog = new ProgressDialog(SkimHistoryActivity.this);
		progressDialog.setMessage(getResources().getString(R.string.progress_loading_data));
		progressDialog.setCancelable(false);
		Window window = progressDialog.getWindow();   
	    WindowManager.LayoutParams lp = window.getAttributes();   
	    lp.alpha = 0.7f;// 透明度   
	    lp.dimAmount = 0.5f;// 黑暗度   
	    window.setAttributes(lp);  
        
		sid = ((MyApplication)this.getApplication()).getSessionId();
		skimHistoryListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
					long arg3) {
				SkimHistory skimHistory = skimHistoryList.get(position);
				if(skimHistory.getType() == Constants.SKIM_HISTORY_TYPE_PRODUCT){
					if(!NetworkUtils.isNetworkConnected(SkimHistoryActivity.this)){
						Toast.makeText(
								SkimHistoryActivity.this,
								SkimHistoryActivity.this
										.getString(R.string.network_unavailable_message),
								Toast.LENGTH_LONG).show();
					}else{
							progressDialog.show();
							HashMap<String, String> parameters = new HashMap<String, String>();
							parameters.put("goodsid", skimHistoryList.get(position).getGoodsid());
							parameters.put("sid", sid);
							httpRequester.getGoodsDetail(parameters);
					}
				}
			}
		});
        
        goodsDetailHandler = new Handler(){
		    @Override
		    public void handleMessage(Message msg) {
		        super.handleMessage(msg);
		        Bundle data = msg.getData();
		        progressDialog.cancel();
		        
		        boolean isError = data.getBoolean(Constants.IS_ERROR);
		        if(isError){
					Toast.makeText(
							SkimHistoryActivity.this,
							SkimHistoryActivity.this
									.getString(R.string.load_data_failure),
							Toast.LENGTH_LONG).show();
		        }
		        
		        Product product = (Product) data.getSerializable(Constants.PRODUCT);
		        
		        Intent intent = new Intent(SkimHistoryActivity.this, ProductDetailActivity.class);
				if(product.getCompare() != null && product.getCompare().getMallnum() > 1){
					intent.putExtra(Constants.PRODUCT_IS_PARITY, true);
					intent = new Intent(SkimHistoryActivity.this, ProductParityActivity.class);
//						List<Mall> mallList = product.getCompare().getMalls();
//						if(mallList != null){
//							for(Mall mall : mallList){
//								if(mall.getMallid().equals(product.getMallid())){
//									intent.putExtra(Constants.PRODUCT_COMPARE_MALL, mall);
//									break;
//								}
//							}
//						}
				}else{
					intent.putExtra(Constants.PRODUCT_IS_PARITY, false);
		    	}
				intent.putExtra(Constants.PRODUCT, product);
				startActivity(intent);
				overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
		    }
        };
        httpRequester = new HttpRequester(this,1, goodsDetailHandler);
	}
	
	public void removeHistory(View view){

		AlertDialog.Builder builder = new Builder(SkimHistoryActivity.this);
		builder.setTitle(SkimHistoryActivity.this.getString(R.string.clear_skim_history_title));
		builder.setMessage(SkimHistoryActivity.this.getString(R.string.clear_skim_history_message));

		builder.setPositiveButton(SkimHistoryActivity.this.getString(R.string.confirm),
				new OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog,
							int which) {
						dialog.dismiss();
						if(skimHistoryList.size() > 0){
							databaseManager.deleteSkimHistory();
							skimHistoryListView.setVisibility(View.GONE);
							tv_no_record.setVisibility(View.VISIBLE);
						}
					}
				});

		builder.setNegativeButton(SkimHistoryActivity.this.getString(R.string.cancel),
				new OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog,
							int which) {
						dialog.dismiss();
					}
				});
		Dialog noticeDialog = builder.create();
		noticeDialog.show();

	}
	
	public void back(View view) {
		this.finish();
		overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
	}
	
	@Override
	protected void onResume() {
		skimHistoryList.removeAll(skimHistoryList);
		if(databaseManager.getSkimHistory().size() > 0){
			skimHistoryListView.setVisibility(View.VISIBLE);
			tv_no_record.setVisibility(View.GONE);
			skimHistoryList.addAll(databaseManager.getSkimHistory());
			skimHistoryListAdapter.notifyDataSetChanged();
		}else{
			skimHistoryListView.setVisibility(View.GONE);
			tv_no_record.setVisibility(View.VISIBLE);
		}

		super.onResume();
	}
	
	@Override
	protected void onDestroy() {
		databaseManager.closeDB();
		skimHistoryListAdapter.close();
		super.onDestroy();
	}
	
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		//如果按下的是返回键，并且没有重复
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			finish();
			overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
			return false;
		}
		return false;
	}

}
